# -*- coding: utf-8 -*-
# @Time : 2022/2/7 11:47

from src.ApiTest.ProjectConfig.Database.baseInfo_database import BaseInfoConfig, BaseInfoConfigSchema
from src.User.Database.user_database import User, UserSchema
from Common.yaml_method import YamlMethod
import ast
from sqlalchemy import and_


class BaseList:
    """
    获取配置列表接口
    """

    @staticmethod
    def base_list(page, limit, system_name, user_id, project_id):
        """
        获取URL配置列表接口
        :param page: 页码
        :param limit: 每页多少条数据
        :param system_name: 系统名称
        :param user_id: user_id
        :param project_id: 项目ID
        :return:
        """

        code = YamlMethod().read_data('code.yaml')['code']

        if project_id:
            if system_name:
                # projectId和systemName都不为空
                data = BaseInfoConfig.query.filter_by(systemName=system_name, projectId=project_id)\
                    .paginate(page=page, per_page=limit)
            else:
                # projectId不为空，systemName都为空
                data = BaseInfoConfig.query.filter_by(projectId=project_id).paginate(page=page, per_page=limit)
        else:
            # 先查询用户所属项目信息
            user = User.query.filter_by(id=user_id).first()
            user_schema = UserSchema()
            user_data = user_schema.dump(user)
            user_project_id = user_data['user_projects']
            id_list = ast.literal_eval(user_project_id)
            # 开始构建过滤条件
            filters = [BaseInfoConfig.projectId.in_(id_list)]
            if system_name:
                # projectId为空，configName不为空
                filters.append(BaseInfoConfig.systemName == system_name)
                data = BaseInfoConfig.query.filter(and_(*filters)).paginate(page=page, per_page=limit)
            else:
                # projectId和configName都为空
                data = BaseInfoConfig.query.filter(BaseInfoConfig.projectId.in_(id_list)).paginate(page=page, per_page=limit)

        info = []
        if data:
            for i in data.items:
                system_schema = BaseInfoConfigSchema()
                system_data = system_schema.dump(i)
                # 将单条URL信息添加到info中
                info.append(system_data)

        total = data.total
        res = {
            'code': code[0],
            'message': 'success',
            'data': {
                'UrlList': info,
                'total': total
            }
        }

        return res
